import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/camera/front_camera_head/front_camera_head_page.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_browser/pages/bean/check_in_record_brower_for_type_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_add_admin_list/binding_add_admin_list_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/add_device_administrator_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_modify_order/terminal_detail_modify_order_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../app_main.dart';

class AddDeviceAdministratorWidget extends StatefulWidget {
  final String deviceCode;

  const AddDeviceAdministratorWidget({Key key, this.deviceCode})
      : super(key: key);

  @override
  _AddDeviceAdministratorWidgetState createState() =>
      _AddDeviceAdministratorWidgetState();

  static Future<dynamic> navigatorPush(
      BuildContext context, String deviceCode) {
    return RouterUtils.routeForFutureResult<AdminListBean>(
      context,
      AddDeviceAdministratorWidget(
        deviceCode: deviceCode,
      ),
    );
  }
}

class _AddDeviceAdministratorWidgetState
    extends BaseState<AddDeviceAdministratorWidget> {
  TerminalDetailModifyOrderViewModel viewModel;
  CommonListPageWidgetState<AdminListBean, AddDeviceAdministratorBean> _mState;
  StreamSubscription streamSubscription;
  @override
  void initState() {
    super.initState();
    viewModel = TerminalDetailModifyOrderViewModel(this);
    streamSubscription =  VgEventBus.global.on<AddAdminRefreshEvent>().listen((event) {
      _mState?.viewModel?.refresh();
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    streamSubscription.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF191E31),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            _toTopBarWidget(),
            SizedBox(
              width: 15,
            ),
            Expanded(
                child: Container(
                    color:
                        ThemeRepository.getInstance().getCardBgColor_21263C(),
                    child: _deviceAdminListDataWidget())),
          ],
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "管理员",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return GestureDetector(
      onTap: () {
        BindingAddAdminListPage.navigatorPush(context,widget?.deviceCode);
      },
      child: Text(
        "+添加",
        style: TextStyle(color: Colors.blue, fontSize: 14),
      ),
    );
  }

  Widget _deviceAdminListDataWidget() {
    return CommonListPageWidget<AdminListBean, AddDeviceAdministratorBean>(
      enablePullDown: false,
      enablePullUp: false,
      netUrl:ServerApi.BASE_URL + "app/appTerminalAdminList",
      httpType: VgHttpType.get,
      queryMapFunc:(int page) =>{
        "authId": UserRepository.getInstance().authId ?? "",
        "hsn": widget.deviceCode,
        // "hsn": "a69ab51225adaf8b",
      },
      //response获取到json数据
      parseDataFunc: (VgHttpResponse response) {
        AddDeviceAdministratorBean adminListBean =
            AddDeviceAdministratorBean.fromMap(response?.data);
        return adminListBean;
      },
      itemBuilder:
          (BuildContext context, int index, AdminListBean adminListBean) {
        return _toAdminListItemWidget(context, index, adminListBean);
      },
      //父组件获取子组件的状态
      stateFunc:
          (CommonListPageWidgetState<AdminListBean, AddDeviceAdministratorBean>
              state) {
        _mState = state;
      },
      //分割器构造器
      // separatorBuilder: (context, int index, _) {
      //   return Container(
      //     height: 0.5,
      //     color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      //     padding: const EdgeInsets.only(left: 15),
      //     child: Container(
      //       color: Color(0xFF303546),
      //     ),
      //   );
      //   // return divider;
      // },
    );
  }

  void _showMenuDialog(BuildContext context,AdminListBean adminListBean){
    CommonMoreMenuDialog.navigatorPushDialog(context,{
      "移除":() async {
        bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定取消${adminListBean?.nick}在该终端下的管理员资格？",
            cancelText: "取消",
            confirmText: "确定",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355());
        if (result ?? false) {
          viewModel?.removeTerminalAdmin(context, widget.deviceCode, adminListBean?.userid);
        }
        setState(() {

        });
      }
    });
  }

  Widget _toAdminListItemWidget(
      BuildContext context, int index, AdminListBean adminListBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        PersonDetailPage.navigatorPush(context, adminListBean?.fuid);
      },
      onLongPress: (){
        if(adminListBean?.roleid=="99" || UserRepository.getInstance().userData.comUser.roleid != "99"){
          return;
        }
        _showMenuDialog(context,adminListBean);
      },
      child: Container(
        height: 64,
        decoration: BoxDecoration(shape: BoxShape.circle),
        margin: const EdgeInsets.symmetric(horizontal: 15),
        // padding: const EdgeInsets.only(left: 15),
        child: Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(32),
              child: VgCacheNetWorkImage(
                showOriginEmptyStr(adminListBean?.napicurl) ??
                    (adminListBean?.napicurl ?? ""),
                defaultErrorType: ImageErrorType.head,
                defaultPlaceType: ImagePlaceType.head,
                height: 40,
                width: 40,
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: _toAdminInformationList(adminListBean),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toAdminInformationList(AdminListBean adminListBean) {
    bool _lastTimeJudge =
        VgDateTimeUtils.getFormatTimeStr(adminListBean?.applogintime)
            ?.contains("今天");
    String _lastTime =
        VgDateTimeUtils.getFormatTimeStr(adminListBean?.applogintime);
    return Column(
      children: <Widget>[
        SizedBox(
          height: 12,
        ),
        Row(
          children: <Widget>[
            Text(
              "${adminListBean?.nick}",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15),
            ),
            SizedBox(
              width: 5,
            ),
            Container(
              child: _roleidJudge(adminListBean?.roleid, adminListBean?.hsn),
            ),
            _toPhoneWidget(adminListBean)
          ],
        ),
        Row(
          children: <Widget>[
            // Text(
            //   "${adminListBean?.loginphone}",
            //   maxLines: 1,
            //   overflow: TextOverflow.ellipsis,
            //   style: TextStyle(color: VgColors.INPUT_BG_COLOR, fontSize: 12),
            // ),
            Container(
              child: _lastTimeJudgeWidget(_lastTimeJudge, _lastTime),
            ),
          ],
        ),
      ],
    );
  }

  Widget _lastTimeJudgeWidget(bool _lastTimeJudge, String _lastTime) {
    if (_lastTime!=null && _lastTime!="") {
      return Text(
        "${"${_lastTime}登录APP"}",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 11,
        ),
        textAlign: TextAlign.right,
      );
    }
    return Text(
      "未登录APP",
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        color: Color(0xFFF95355),
        fontSize: 11,
      ),
      textAlign: TextAlign.right,
    );
  }

  Widget _toPhoneWidget(AdminListBean itemBean) {
    return Offstage(
      offstage: itemBean?.loginphone == null || itemBean?.loginphone?.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(itemBean?.loginphone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  Widget _roleidJudge(String roleid, String hsn) {
    if (roleid == "99") {
      return VgLabelUtils.getRoleLabel(roleid);
    }
    if (hsn != null && hsn != "") {
      return VgLabelUtils.getCurrentLoginDeviceLabel("01");
    }
    return Container();
  }
}
